package com.example.demo.qy.task;

import com.alibaba.fastjson.JSON;
import com.example.demo.qy.model.Weather;
import com.example.demo.qy.model.WeatherFuture;
import com.example.demo.qy.service.WeatherFutureService;
import com.example.demo.qy.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class WeatherTask {

    @Autowired
    private WeatherService weatherService;
    @Autowired
    private WeatherFutureService weatherFutureService;

    //@Scheduled(cron="0 0 12 */1 * ?")
    @Scheduled(cron="0 0 */1 * * ?")
    public void saveWeather(){

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(
                "http://apicloud.mob.com/v1/weather/query?key=25a6bd8a6e5f0&city=秦皇岛&province=北京",
                HttpMethod.GET,
                null,
                String.class);
        System.out.println(response.getBody());
        Map res = JSON.toJavaObject(JSON.parseObject(response.getBody()),Map.class);
        List result = JSON.toJavaObject((JSON) JSON.toJSON(res.get("result")),List.class);
        Map data = JSON.toJavaObject((JSON) JSON.toJSON(result.get(0)),Map.class);

        List weatherFutures = JSON.toJavaObject((JSON) JSON.toJSON(data.get("future")),List.class);
        List<WeatherFuture> futures = new ArrayList();
        for (int i = 0; i < weatherFutures.size(); i++) {
            WeatherFuture weatherFuture = JSON.toJavaObject((JSON) JSON.toJSON(weatherFutures.get(i)),WeatherFuture.class);
            weatherFutureService.save(weatherFuture);
            WeatherFuture weatherFuture1 = new WeatherFuture();
            weatherFuture1.setId(weatherFuture.getId());
            futures.add(weatherFuture1);
        }

        Weather weather = new Weather();
        weather.setAirCondition((String) data.get("airCondition"));
        weather.setApiUpdateTime(Long.valueOf(data.get("updateTime")+""));
        weather.setCity((String) data.get("city"));
        weather.setColdIndex((String) data.get("coldIndex"));
        weather.setDate((String) data.get("date"));
        weather.setDistrct((String) data.get("distrct"));
        weather.setDressingIndex((String) data.get("dressingIndex"));
        weather.setExerciseIndex((String) data.get("exerciseIndex"));
        weather.setFutureList(futures);
        weatherService.save(weather);

    }

}
